package servlets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import actionForm.GetContactByIdValidationForm;
import domain.Contact;
import domain.IDAOContact;
import domain.IDAOContactGroup;

public class GetContactByIdAction extends Action {

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(getServlet().getServletContext());
		if (request.getMethod().equals("POST")){
			GetContactByIdValidationForm gform = (GetContactByIdValidationForm) form;
			IDAOContact dao = (IDAOContact) context.getBean("daocontact");
			IDAOContactGroup daog = (IDAOContactGroup) context.getBean("daocontactgroup");
			request.setAttribute("groups", daog.getContactGroups().toArray());
			Contact contact = dao.getContact(Long.valueOf(gform.getId()));
			if ( contact != null ) {
				request.setAttribute("contact", contact );
				return mapping.findForward("modifyContact");
			}
			else {
				request.setAttribute("errorMessage", "The contact doesn't exist.");
				return mapping.findForward("error");		
			}
		}
		return null;
	}
}
